<template>
  <div>
    <canvas id="canvas"></canvas>
  </div>
</template>
<script>
export default {
  name: 'testB',
  data () {
    return {
      img: 'http://img3.imgtn.bdimg.com/it/u=3543954389,1979127086&fm=26&gp=0.jpg'
    }
  },
  mounted () {
    let type = "circle";
    let radius = 10;
    let erasing = false;
    let savedImage = null;
    const canvas = document.getElementById("canvas");
    const context = canvas.getContext("2d");
    const image = new Image();
    image.src = this.img;
    image.onload = () => {
      drawFlashImage();
      saveImage(); //第一次把图像存下来
    };
    canvas.addEventListener("mousedown", e => {
      erasing = true;
    });

    canvas.addEventListener("mousemove", e => {
      const { x, y } = windowToCanvas(canvas, e.clientX, e.clientY);
      if (erasing) {
        erase(x, y);
      } else {
        context.clearRect(0, 0, canvas.width, canvas.height);
        restoreImage();
        // drawEraser(x, y);
      }
    });
    canvas.addEventListener("mouseup", e => {
      erasing = false;
      saveImage();
      context.clearRect(0, 0, canvas.width, canvas.height);
      restoreImage();
    });
    function erase (x, y) {
      context.save();
      context.beginPath();
      context.fillStyle = "#ffffff";
      if (type === "circle") {
        context.arc(x, y, radius, 0, Math.PI * 2, true);
        context.fill();
      } else {
        context.fillRect(x - radius / 2, y - radius / 2, radius, radius);
      }
      context.restore();
    }
    function drawFlashImage () {
      context.drawImage(image, 0, 0, canvas.width, canvas.height);
    }
    function saveImage () {
      savedImage = context.getImageData(0, 0, canvas.width, canvas.height);
    }
    function restoreImage () {
      context.putImageData(savedImage, 0, 0);
    }
    function windowToCanvas (canvas, x, y) {
      var bbox = canvas.getBoundingClientRect();
      var style = window.getComputedStyle(canvas);
      return {
        x:
          (x -
            bbox.left -
            parseInt(style.paddingLeft) -
            parseInt(style.borderLeft)) *
          (canvas.width / parseInt(style.width)),
        y:
          (y - bbox.top - parseInt(style.paddingTop) - parseInt(style.borderTop)) *
          (canvas.height / parseInt(style.height))
      };
    }
  }
}
</script>
<style scoped>
</style>